package com.example.unit.test.demo.sender;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.fc.client.FunctionComputeClient;
import com.aliyuncs.fc.constants.Const;
import com.aliyuncs.fc.request.InvokeFunctionRequest;
import com.aliyuncs.fc.response.InvokeFunctionResponse;
import com.example.unit.test.demo.pojo.entity.UserEntity;

import java.nio.charset.StandardCharsets;

/**
 * FunctionSender
 *
 * @author lijiadong
 * @date 2023/2/3 19:47
 */
public class FunctionSender {

    private FunctionComputeClient functionClient;

    private static class FcSenderSingleton {
        private static FunctionSender instance = new FunctionSender();
    }

    public static FunctionSender getInstance() {
        return FcSenderSingleton.instance;
    }

    private FunctionSender() {
        // 初始化调用函数客户端。
        functionClient = new FunctionComputeClient("region", "uid",
                "key", "secret");
    }


    public InvokeFunctionResponse testSendUserInfo(UserEntity entity, String funcName) {

        InvokeFunctionRequest request = new InvokeFunctionRequest("serviceName", funcName);
        request.setInvocationType(Const.INVOCATION_TYPE_ASYNC);

        JSONObject param = JSON.parseObject(JSON.toJSONString(entity));
        request.setPayload(JSON.toJSONString(param).getBytes(StandardCharsets.UTF_8));
        // 执行函数
        return functionClient.invokeFunction(request);
    }

}
